package com.example.rxjavademo;

import android.util.Log;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * @author COCO
 * @date 2019/3/26
 */
public class TransformerUtils {

    public static ObservableTransformer<String, Integer> applyTransformer() {
        return new ObservableTransformer<String, Integer>() {
            @Override
            public ObservableSource<Integer> apply(Observable<String> upstream) {
                return upstream.map(new Function<String, Integer>() {
                    @Override
                    public Integer apply(String s) throws Exception {
                        Log.i("COCO", "transformer: " + s + ", length:" + s.length());
                        return s.length();
                    }
                });
            }
        };
    }

    //泛型方法：①返回值前面<T> ②返回值泛型
    public static <T> ObservableTransformer<T, T> observableToMain() {
        return new ObservableTransformer<T, T>() {
            @Override
            public ObservableSource<T> apply(Observable<T> upstream) {
                return upstream.subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }
}
